package com.leyou.trade.service.impl;


import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author ：qcq
 * @date ：Created in 2020/12/21 13:57
 * @description：
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository repository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addCart(CartItem cartItem) {

        Long userId = UserContext.getUser().getId();

        String id = createId(cartItem.getSkuId());
        Optional<CartItem> itemRepository = this.repository.findById(id);
        if (itemRepository.isPresent()) {
            CartItem item = itemRepository.get();
            Integer num = cartItem.getNum();
            cartItem.setNum(num+item.getNum());
        }

        cartItem.setId(id);
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        this.repository.save(cartItem);

    }

    @Override
    public List<CartItem> queryCartList() {

        Long userId = UserContext.getUser().getId();

        List<CartItem> cartItems = repository.findByUserId(userId);

        return cartItems;
    }

    @Override
    public void updateCart(Long id, Integer num) {
        mongoTemplate.update(CartItem.class)
                .matching(Query.query(Criteria.where("_id").is(createId(id))))
                .apply(Update.update("num", num).currentDate("updateTime"))
                .first();
    }

    @Override
    public void deleteCart(Long skuId) {
        repository.deleteBySkuId(skuId);
    }

    private String createId(Long skuId){
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }

}
